import { getEx, post,update,remove } from './crud'

export function queryThing(condition){
  return new Promise((re,rej)=>{
    getEx("thingQuery","thing?condition=" + condition).then(res=>{
      if(res && res.data && res.data.result){
        re(res.data.result)
      }
    }).catch(err=>{
      rej(err)
    })
  })
}

export function getAllThings() {
  return new Promise((re, rej) => {
      getEx("thingQuery/thingAll").then((res) => {
          if (res?.data?.result) {
              re(res.data.result)
          } else {
              re([])
          }
      }).catch(err => {
          rej(err)
      })
  })
}
export function getThings() {
  return new Promise((re, rej) => {
    getEx("thingQuery/thingAll").then((res) => {
      if (res && res.data && res.data.result) {
        let result = res.data.result
        let cache = {}
        let stations = []
        result.forEach(t => {
          cache[t.uid] = t
          if (t.is_station) {
            t.children = []
            t.state = "-"
            if (t.parent_id == "") {
              stations.push(t)
            }
          }
        });
        result.forEach(t => {
          if (t.station_id) {
            let p = cache[t.station_id]
            if (p) {
              if (!p.children) {
                p.children = []
              }

              p.children.push(t)
            }
          }
          if (t.parent_id) {
            let p = cache[t.parent_id]
            if (p) {
              if (!p.children) {
                p.children = []
              }
              p.children.push(t)
            }
          }
        })
        re(stations, cache)
      }
    }).catch(err => {
      rej(err)
    })
  })

}
function createByFun(fun, citem) {
  return new Promise((re, rej) => {
    let url = "thing";
    if (fun == post) {
      url = "newDev";
    }
    fun(url, citem).then((res) => {
      console.log("***************", res);
      if (res && res.data && res.data.result && res.data.result != "OK") {
        citem.uid = res.data.result.uid;
      }
      if (url == "newDev") {
        re();
        return;
      }
      //if (citem.station) {
      console.log(citem);
      let ts = {
        thing_id: citem.uid,
        station_id: citem.station ? citem.station.uid : citem.station_id
      }
      if (ts.station_id == '' || ts.station_id == undefined) {
        rej()
        return
      }
      fun("thingstation", ts)
        .catch((err) => {
          rej(err);
        })
        .then(() => {
          //let itemparams = item.params
          let setParams = {
            thing_id: citem.uid,
            values: citem.params,
          };
          fun("thingparam", setParams);
          re();
        })
        .catch((err) => {
          rej(err);
        });
      //}
    });
  });
}
export async function thingAction(fun, owner, item, count) {
  //const item = dlg.$data.item
  const _this = owner;
  if (count == undefined) {
    count = 1;
  }
  let name = item.s_name;
  if (!name) {
    name = item.model_id;
  }
  _this.spinning = true;
  if (_this.station && !item.station_id && item.station_id != _this.station.uid) {
    item.station_id = _this.station.uid;
  }

  let sitem = JSON.stringify(item);
  let citem = JSON.parse(sitem);
  citem.count = count;
  try {
    await createByFun(fun, citem);
  } catch (err) {
    console.log("----------------create fun------", err);
  }

  _this.spinning = false;
  _this.refresh();
}

export function editActiveThing(window,thingDlg) {
  //window.spinning = true;
  let activeThing = window.$store.state.thingView.activeThing
  const thing = JSON.parse(JSON.stringify(activeThing.info)); //Object.assign({}, child);
  let item = thing.Thing;
  item.lat = activeThing.backInfo.lat;
  item.lon = activeThing.backInfo.lon;
  if (thing.Params) {
    item.params = [];
    for (let p in thing.Params) {
      item.params.push({ param_id: p, param_value: thing.Params[p] });
    }
  }
  item.station_id = thing.station_id;

  item.isNew = false;
  item.station = window.station;
  thingDlg.Show(
    (owner, dlg) => {
      const item = dlg.$data.item;
      console.log("update item--------------", item);
      return thingAction(update, owner, item);
    },
    window,
    item
  );
  //window.spinning = false;

}

export function createThing(item){
  return new Promise((re,rej)=>{
    if(!item.count){
      item.count = 1
    }
    if(!item.station_id){
      rej("站点id为空，无法创建")
      return
    }
    createByFun(post,item).then(()=>{
      re()
    }).catch(err=>{
      rej(err)
    })
  })
   
}

export function saveThing(item){
  return new Promise((re,rej)=>{
    
    if(!item.station_id){
      rej("站点id为空，无法创建")
      return
    }
    createByFun(update,item).then(()=>{
      re()
    }).catch(err=>{
      rej(err)
    })
  })
}

export function deleteThing(item){
  return remove("thing", item.uid)
}

export function getThingsOnline(){
  return new Promise((re,rej)=>{
      getEx("thingQuery/thing/online").then(res=>{
          if(res?.data?.result){
              re(res.data.result)
          }
      }).catch(err=>{
          rej(err)
      })
  })
 
}

export default {
  getThings,
  thingAction,
  editActiveThing,
  createThing,
  saveThing,
  deleteThing,
  queryThing,
  getThingsOnline,
  getAllThings,
}